package com.zhijian.warehouse.manage.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class RequestPreHandler implements HandlerInterceptor, RequestTracker {
    public static final Logger log = LoggerFactory.getLogger(RequestPreHandler.class);
    private static Long startTime = null;

    public RequestPreHandler() {
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (startTime == null)
            startTime = System.currentTimeMillis();
        if (!(handler instanceof HandlerMethod)) {
            return true;
        } else {
            log.info("{}| request start", request.getServletPath());
            this.createTrackId(request);
            return true;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("{}| request end, times: {} ms", request.getServletPath(), startTime == null ? -1 : System.currentTimeMillis() - startTime);
        startTime = null;
        this.clearTrackId();
    }

}
